﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Threading;

namespace BookInfoExtractor
{
    public partial class ISBNExtractor : Form
    {
        Queue<string> detailsUrlQueue;
        string currentUrl = string.Empty;
       
        public ISBNExtractor()
        {
            InitializeComponent();
        }

        public void FormLoader()
        {
            //this.Show();
            //detailsUrlQueue = new Queue<string>();
            //foreach (BookInfo _bi in Form1.lstBookInfo)
            //{
            //    detailsUrlQueue.Enqueue(_bi.DetailsUrl);
            //}
            //webBrowser1.Url = new Uri(detailsUrlQueue.Dequeue());
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            Application.DoEvents();

            if (webBrowser1.ReadyState == WebBrowserReadyState.Complete || webBrowser1.ReadyState == WebBrowserReadyState.Interactive)
            {
                foreach (HtmlElement node in webBrowser1.Document.All)
                {
                    bool isISBNFound = false;
                    if (node.InnerText != null && node.InnerText.ToLower().Contains("isbn"))
                    {
                        string innerText = node.InnerText.ToLower();
                        //ISBN in this case will be of the format 
                        //(text) isbn (space separated possibly) (number - 10/13 digit) 
                        //number possibly separated by "-" delimiter

                        //find isbn in innerText string
                        int startIdx = innerText.IndexOf("isbn");

                        if (startIdx == 0)
                        {
                            if (node.NextSibling != null && node.NextSibling.InnerText != null)
                            {
                                string nextNodeText = node.NextSibling.InnerText.Trim();
                                if (!string.IsNullOrEmpty(nextNodeText))
                                {
                                    if (nextNodeText.Length == 10 || nextNodeText.Length == 13)
                                    {
                                        innerText = nextNodeText;
                                    }
                                }
                            }
                        }

                        string isbnStart = innerText.Substring(startIdx);

                        //try to find first delimiter out of possibles
                        //":" " "(space) "-"
                        int delimiterIdx = isbnStart.IndexOf(':');
                        if (delimiterIdx == -1)
                            delimiterIdx = isbnStart.IndexOf(' ');

                        isbnStart = isbnStart.Substring(delimiterIdx + 1);

                        //then get the isbn number with any other characters like :, ' ', - around it.
                        //count the chars till you find an alphabet indicating isbn is now over.
                        int isbnChrCtr = 0;
                        foreach (char chr in isbnStart.ToCharArray())
                        {
                            if (chr == ' ' || char.IsSymbol(chr) || char.IsSeparator(chr) || char.IsPunctuation(chr))
                            {
                                isbnChrCtr++;
                                continue;
                            }

                            if (char.IsDigit(chr))
                                isbnChrCtr++;

                            if (char.IsLetter(chr))
                                break;
                        }

                        isbnStart = isbnStart.Substring(0, isbnChrCtr);

                        char[] isbnCharArray = isbnStart.ToCharArray();

                        string isbnNumber = string.Empty;
                        for (int cnt = 0; cnt < isbnCharArray.Length; cnt++)
                        {
                            if (!char.IsDigit(isbnCharArray[cnt]))
                                isbnStart = isbnStart.Remove(isbnStart.IndexOf(isbnCharArray[cnt]), 1);
                        }

                        isbnNumber = isbnStart;

                        if (isbnNumber.Length == 10 || isbnNumber.Length == 13)
                        {
                            foreach (BookInfo obj in Form1.lstBookInfo)
                            {
                                if (obj.DetailsUrl == currentUrl)
                                {
                                    obj.ISBN = isbnNumber;
                                    isISBNFound = true;
                                    break;
                                }
                            }

                        }

                        if (isISBNFound)
                            break;
                    }
                }

                if (detailsUrlQueue.Count > 0)
                {
                    currentUrl = detailsUrlQueue.Dequeue();
                    webBrowser1.Navigate(currentUrl);
                }
                else
                {
                    this.Close();
                }
            }
        }

        private void ISBNExtractor_Load(object sender, EventArgs e)
        {
            //FormLoader("http://www.barnesandnoble.com/w/inferno-dan-brown/1114144951?ean=9780385537858");
            //tried out above logic for popular, goodreads, openisbn, worked smoothly!
            //need to add break and other stuff.. 

            detailsUrlQueue = new Queue<string>();
            foreach (BookInfo _bi in Form1.lstBookInfo)
            {
                detailsUrlQueue.Enqueue(_bi.DetailsUrl);
            }
            currentUrl = detailsUrlQueue.Dequeue();
            webBrowser1.ScriptErrorsSuppressed = true;
            webBrowser1.Url = new Uri(currentUrl);
        }
    }
}
